package com.jjzhk.common.handler;

import com.jjzhk.common.utils.ReflexUtils;
import com.jjzhk.common.utils.SerializationUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * RpcDecoder
 *
 * @author : JJZHK
 * @date : 2016-08-14
 * @comments :
 **/
public class RpcDecoder extends ByteToMessageDecoder{
    private Class<?> genericClass;
    private Class<?> forSerialization;

    public RpcDecoder(Class<?> genericClass, Class<?> forSerialization) {
        this.genericClass = genericClass;
        this.forSerialization = forSerialization;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4)
        {
            return;
        }

        in.markReaderIndex();
        int length = in.readInt();
        if (in.readableBytes() < length)
        {
            in.resetReaderIndex();
            return;
        }

        byte[] data = new byte[length];
        in.readBytes(data);

        SerializationUtils obj = ReflexUtils.newObject((Class<SerializationUtils>) this.forSerialization);

        out.add(obj.deserialize(data, genericClass));
    }
}
